package com.platform.user.websocket;


import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionPool {

    public static Map<String, Session> sessions = new ConcurrentHashMap<>();//避免多线程问题

    // 根据用户id，查询该用户所有的会话
    public static Map<String, List<Session>> userToSessionListMap = new ConcurrentHashMap<>();

    // 根据聊天室id，查询所有在聊天室的session
    public static Map<String, List<Session>> roomToSessionListMap = new ConcurrentHashMap<>();

    // session锁
    public static Map<String, Object> sessionLocks = new ConcurrentHashMap<>(); // 锁对象映射

    public static void close(String sessionId) {
        //sessionId是在session中添加了一个标识，准确定位某条session
        for (String userId : SessionPool.sessions.keySet()) {
            Session session = SessionPool.sessions.get(userId);
            if (session.getId().equals(sessionId)) {
                sessions.remove(userId);
                break;
            }
        }
    }

    public static void sendMessage(String userId, String message) {
        sessions.get(userId).getAsyncRemote().sendText(message);
    }

    //消息的群发，业务逻辑的群发
    public static void sendMessage(String message) {
        for (String sessionId : SessionPool.sessions.keySet()) {
            SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(message);
        }
    }

    //点对点的消息推送
    public static void sendMessage(Map<String, Object> params) {
        String userId = params.get("fromUserId").toString();
        String toUserId = params.get("toUserId").toString();
        String msg = params.get("message").toString();
        String timeStamp = params.get("timeStamp").toString();
        String type = params.get("messageType").toString();
        //获取用户session
        Session session = sessions.get(toUserId);
        // todo 根据userId和roomId，获取到当前聊天室在线用户的sessionList

        msg = userId + " " + toUserId + " " + timeStamp + " " + type + " " + msg;
        //session不为空的情况下进行点对点推送
        if (session != null) {
            session.getAsyncRemote().sendText(msg);
        } else {

//            TbMessage tbMessage = new TbMessage();
//            tbMessage.setToUserId(toUserId);
//            tbMessage.setFromUserId(userId);
//            tbMessage.setMessage(msg);
//            tbMessage.setTimeStamp(timeStamp);
//            tbMessage.setMessageType(Integer.valueOf(type));
//            tbMessageDao.insert(tbMessage);
            System.out.println("存数据库的数据：" + msg);
        }
    }


    //——————————————————————————————————————————————————————————————————————————

    // 根据用户id，查询当前用户在线的聊天室id列表
    // public static Map<Integer, List<Integer>> userToRoomListMap = new ConcurrentHashMap<>();

    // 根据聊天室id，查询当前聊天室在线的用户id列表
    // public static Map<Integer, List<Integer>> roomToUserListMap = new ConcurrentHashMap<>();
}